package com.suncky.frame.base;

import android.view.LayoutInflater;
import android.view.View;

import androidx.viewbinding.ViewBinding;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

public class BaseViewBindingActivity<B extends ViewBinding> extends BaseActivity {

    private B binding;

    @SuppressWarnings("unchecked")
    protected B createBinding() {
        try {
            // 获取当前对象的父类类型
            ParameterizedType pt = (ParameterizedType) (this.getClass().getGenericSuperclass());
            if (pt!=null) {
                // 获取第一个类型参数的真实类型
                Class<B> c = (Class<B>) pt.getActualTypeArguments()[0];
                Method method = c.getDeclaredMethod("inflate", LayoutInflater.class);
                return (B) method.invoke(null, getLayoutInflater());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public B getBinding() {
        return binding;
    }

    @Override
    protected View getContentView() {
        if (binding == null) {
            binding = createBinding();
        }
        if (binding != null) {
            return binding.getRoot();
        }
        return null;
    }

    @Override
    protected final int getLayoutResId() {
        return 0;
    }
}
